package com.leonyr.smartipaddemo.crop;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.leonyr.mvvm.act.Common;
import com.leonyr.mvvm.frag.AbBindFragment;
import com.leonyr.mvvm.util.RxSchedulers;
import com.leonyr.smartipaddemo.R;
import com.leonyr.smartipaddemo.base.photo.IImageView;
import com.leonyr.smartipaddemo.bean.PicItem;
import com.leonyr.smartipaddemo.databinding.FmCropImageBinding;

import org.parceler.Parcel;
import org.parceler.ParcelConstructor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class CropImageFragment extends AbBindFragment<CropImageViewHolder, FmCropImageBinding> implements IImageView {

    private static final String EXTRA_FROM_ALBUM = "extra_from_album";
    public static final String EXTRA_CROPPED_FILE = "extra_cropped_file";
    private static final int REQUEST_CODE_TAKE_PHOTO = 100;
    private static final int REQUEST_CODE_SELECT_ALBUM = 200;

    //    public static String cropFile;
    private Bitmap bitmap_def;
    private static ArrayList<String> cropFiles;
    private static final String EXTRA_CROP_FILE_PATH = "extra_crop_file_path";
    Disposable tempDisposable;
    ProgressDialog mProgressDialog;
    private boolean isCrop;
    private ArrayList<String> paths = new ArrayList<>();

    public static CropImageFragment newInstance(ArrayList<String> paths) {
        cropFiles = paths;
        Bundle args = new Bundle();
//        args.putString(EXTRA_CROP_FILE_PATH, cropFilePath);
        CropImageFragment fragment = new CropImageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fm_crop_image;
    }

    /*public static Intent getJumpIntent(Context context, boolean fromAlbum, File croppedFile) {
        Intent intent = new Intent(context, CropActivity.class);
        intent.putExtra(EXTRA_FROM_ALBUM, fromAlbum);
        intent.putExtra(EXTRA_CROPPED_FILE, croppedFile);
        return intent;
    }*/

    @Override
    protected void initView(View rootView, Bundle savedInstanceState) {
        /*Bundle extras = getArguments();
        if (null != extras) {
            cropFile = extras.getString(EXTRA_CROP_FILE_PATH);
        }*/
        setVModel(new CropImageViewHolder(getActivity()));
        getVModel().attachView(this);
        if (null == mProgressDialog) {
            mProgressDialog = new ProgressDialog(mCtx);
//            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        Binding().recylerlist.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        //设置Adapter
        Binding().recylerlist.setAdapter(getVModel().getAdapter());
        //设置分隔线
        //设置增加或删除条目的动画
        Binding().recylerlist.setItemAnimator(new DefaultItemAnimator());
        isCrop = false;
        bitmap_def = Binding().ivCrop.getBitmap();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (cropFiles == null || cropFiles.size() == 0) {
            getFragmentManager().popBackStack();
        }
        Binding().setCropImageFragment(this);

        mProgressDialog.show();
        Observable
                .fromCallable(new Callable<List<PicItem>>() {
                    @Override
                    public List<PicItem> call() throws Exception {
                        List<PicItem> list = new ArrayList<>();
                        BitmapFactory.Options options = new BitmapFactory.Options();
//                        int pos = 0;
                        for (String path : cropFiles) {
                            options.inJustDecodeBounds = true;
                            BitmapFactory.decodeFile(path, options);
                            options.inJustDecodeBounds = false;
                            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
//                             FileUtil.deleteFile(path);
                            boolean isSelected = false;
//                            if (pos == 0) {
//                                isSelected = true;
//                            }
                            list.add(new PicItem(path, bitmap, false, isSelected));
//                            pos++;
                        }

                        return list;
                    }
                })
//                .map(new Function<Bitmap, Bitmap>() {
//                    @Override
//                    public Bitmap apply(Bitmap bitmap) throws Exception {
//                        return BitmapUtil.rotateBitmap(bitmap, 180);
//                    }
//                })
                .compose(RxSchedulers.IOMain())
                .subscribe(new Observer<List<PicItem>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        tempDisposable = d;
                    }

                    @Override
                    public void onNext(List<PicItem> bitmaps) {
//
                        if (bitmaps != null && bitmaps.size() > 0) {
                            changeImageState(true);
                            getVModel().reflesh(bitmaps);
                            //
//                            Binding().ivCrop.setImageToCrop(bitmaps.get(0).getBitmap());
                            if (!isCrop) {
                                changeViewState();
                            }
//                            getVModel().setLastID(0);
                            Log.e("ImageAdapter", "-------------------------------------------------------------------------1");
                        } else {
                            changeImageState(false);
                            Log.e("ImageAdapter", "-------------------------------------------------------------------------2");
                        }

                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        getActivity().onBackPressed();
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                if (isCrop) {
                    changeViewState();
//                    Binding().ivCrop.setImageBitmap(bitmap_def);
                    Binding().ivCrop.setFullImgCrop();
                    return;
                }
                if (getVModel().getItemCounter() > 0) {
                    paths.addAll(getVModel().getPaths());
                }
                if (paths.size() > 0) {
                    Intent intent = new Intent();
                    intent.putStringArrayListExtra(EXTRA_CROPPED_FILE, paths);
                    setResult(Activity.RESULT_OK, intent);
                } else {
                    getFragmentManager().popBackStack();
                }
                break;
            case R.id.btn_ok:
                if (!isCrop) {
                    Toast.makeText(getContext(), "请先选择裁剪图片", Toast.LENGTH_SHORT).show();
                    return;
                }
                mProgressDialog.show();
                Observable
                        .fromCallable(new Callable<Boolean>() {
                            @Override
                            public Boolean call() throws Exception {
                                File mCroppedFile = new File(getVModel().getCurrentPath());
                                Intent intent = new Intent();
                                intent.putExtra(EXTRA_CROPPED_FILE, mCroppedFile.getPath());
                                if (Binding().ivCrop.canRightCrop()) {
                                    Bitmap crop = Binding().ivCrop.crop();
                                    if (crop != null) {
                                        saveImage(crop, mCroppedFile);
                                        Log.e("Path", " " + (getVModel() == null) + "  " + (paths == null) + "   " + (getVModel().getCurrentPath() == null));
                                        paths.add(getVModel().getCurrentPath());
                                        return true;
                                    }
                                } else {
                                    Toast.makeText(getContext(), "剪切失败", Toast.LENGTH_SHORT).show();
                                }
                                return false;
                            }
                        }).compose(RxSchedulers.IOMain())
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(Boolean aBoolean) {
                                Toast.makeText(getContext(), "剪切成功", Toast.LENGTH_SHORT).show();
                                if (isCrop) {
                                    changeViewState();
                                    Binding().ivCrop.setImageBitmap(bitmap_def);
                                    getVModel().reset();
                                }
//                                if (getVModel().getItemCounter() > 0) {
//                                    if (getVModel().reset()) {
//                                        BitmapFactory.Options options = new BitmapFactory.Options();
//                                        options.inJustDecodeBounds = true;
//                                        BitmapFactory.decodeFile(getVModel().getCurrentPath(), options);
//                                        options.inJustDecodeBounds = false;
//                                        Bitmap bitmap = BitmapFactory.decodeFile(getVModel().getCurrentPath(), options);
//                                        Binding().ivCrop.setImageBitmap(bitmap);
//                                    }
//                                }
                                mProgressDialog.dismiss();
                                if (getVModel().getItemCounter() == 0) {
                                    if (paths.size() > 0) {
                                        Intent intent = new Intent();
                                        intent.putStringArrayListExtra(EXTRA_CROPPED_FILE, paths);
                                        setResult(Activity.RESULT_OK, intent);
                                    } else {
                                        getFragmentManager().popBackStack();
                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                mProgressDialog.dismiss();
                            }

                            @Override
                            public void onComplete() {

                            }
                        });
                break;
            case R.id.btn_reset: // 重拍
                getVModel().clean();
                getVModel().resetId();
                paths.clear();
                Intent intent1 = new Intent();
                setResult(0x0066, intent1);
                break;
        }
    }


    private void saveImage(Bitmap bitmap, File saveFile) {
        try {
            if (!saveFile.exists()) {
                saveFile.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(saveFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private int calculateSampleSize(BitmapFactory.Options options) {
        int outHeight = options.outHeight;
        int outWidth = options.outWidth;
        int sampleSize = 1;
        int destHeight = 1000;
        int destWidth = 1000;
        if (outHeight > destHeight || outWidth > destHeight) {
            if (outHeight > outWidth) {
                sampleSize = outHeight / destHeight;
            } else {
                sampleSize = outWidth / destWidth;
            }
        }
        if (sampleSize < 1) {
            sampleSize = 1;
        }
        return sampleSize;
    }

    @Override
    public void onDestroy() {
        if (null != tempDisposable && !tempDisposable.isDisposed()) {
            tempDisposable.dispose();
        }
        super.onDestroy();
//        if(getVModel() != null) {
//            getVModel().dispose();
//        }
//        paths.clear();
//        paths = null;
//        bitmap_def = null;
    }

    @Override
    public void changeImageState(boolean state) {
        Binding().llNoDate.setVisibility(state ? View.GONE : View.VISIBLE);
    }

    @Override
    public void cropImage(Bitmap bitmap) {
        Binding().ivCrop.setImageToCrop(bitmap);
        if (!isCrop) {
            changeViewState();
        }
//      Binding().btnOk.setEnabled(true);
    }

    private void changeViewState() {
        if (!isCrop) {
            Binding().btnOk.setVisibility(View.VISIBLE);
            Binding().btnReset.setVisibility(View.GONE);
            Binding().btnBack.setText("不裁剪");
            isCrop = true;
        } else {
            Binding().btnOk.setVisibility(View.GONE);
            Binding().btnReset.setVisibility(View.VISIBLE);
            Binding().btnBack.setText("结束");
            isCrop = false;
        }
    }

    @Parcel
    public static class CropImageType implements Common.Type {

        String savePath;

        @ParcelConstructor
        public CropImageType(String savePath) {
            this.savePath = savePath;
        }

        @NonNull
        @Override
        public AbBindFragment newFragment() {
            return newInstance(new ArrayList<>());
        }

        @NonNull
        @Override
        public String getTag() {
            return CropImageFragment.class.getSimpleName();
        }
    }

}
